<script setup lang="ts">
import { Button, Cell, CellGroup, Field, Icon, Popup, showNotify, Space, Tag, Stepper, RadioGroup, Radio } from 'vant'
import { onBeforeUnmount, onMounted, reactive, Ref, ref } from 'vue'
import GiftView from './components/GiftView.vue'
import { socket } from './socket'

interface PoolLevelData {
    balance: string
    gifts: { price: string; title: string; enable: boolean }[]
}

interface Pool {
    id: number
    price: number
    locked: number[]
    level_2: PoolLevelData
    level_3: PoolLevelData
    level_4: PoolLevelData
    max_gifts: number
}

interface State {
    pools: Pool[]
    special_uids: string[]
    no_record: number
}

let timer: any
onMounted(() => {
    socket.on('blind_box:state', onState)
    socket.on('blind_box:fill_progress', onFillTask)
    socket.on('reconnect', onReconnect)
    socket.emit('blind_box:get_state')
    timer = setInterval(onReconnect, 15000)
})
onBeforeUnmount(() => {
    socket.off('blind_box:state', onState)
    socket.off('blind_box:fill_progress', onFillTask)
    socket.off('reconnect', onReconnect)
    clearInterval(timer)
})
const onReconnect = () => {
    socket.emit('blind_box:get_state')
}

const refreshState = async () => {
    await socket.emitWithAck('blind_box:get_state')
    showNotify({
        message: '数据已更新',
        type: 'success',
    })
}

const state = ref() as Ref<State>

const onState = (v: State) => {
    v.pools.forEach((pool) => {
        pool.max_gifts = Math.max(pool.level_2.gifts.length, pool.level_3.gifts.length, pool.level_4.gifts.length)
    })
    state.value = v
}

const removeUid = async (uid: string) => {
    const next = [...state.value.special_uids].filter((t) => t !== uid)
    await socket.emitWithAck('blind_box:set_special_uids', next)
    showNotify({
        message: '数据已更新',
        type: 'success',
    })
}

const userPopup = reactive({
    show: false,
    value: '',
})

const addUser = async () => {
    let uid = userPopup.value.trim()
    if (uid === '' || !/^[0-9]+$/.test(uid)) {
        userPopup.show = false
        return
    }

    userPopup.show = false
    const next = [...state.value.special_uids, uid]
    await socket.emitWithAck('blind_box:set_special_uids', next)
    showNotify({
        message: '数据已更新',
        type: 'success',
    })
}

const toggleFlag = async (key: string, value: any) => {
    await socket.emitWithAck('blind_box:set_flag', key, value)
    showNotify({
        message: '数据已更新',
        type: 'success',
    })
}

const toggleLocked = async (pool: Pool, level: number) => {
    const locked = [...pool.locked]
    const index = locked.indexOf(level)
    if (index === -1) {
        locked.push(level)
    } else {
        locked.splice(index, 1)
    }
    await socket.emitWithAck('blind_box:lock', pool.id, locked)
    showNotify({
        message: '数据已更新',
        type: 'success',
    })
}

const taskPopup = reactive({
    show: false,
    data: {
        uid: '',
        dealer_id: 0,
        num: 1,
    },
})

/**
 * 生成记录
 */
const fillRecords = () => {
    taskPopup.data.uid = taskPopup.data.uid.trim()
    if (taskPopup.data.uid === '' || !/^[0-9]+$/.test(taskPopup.data.uid)) {
        return
    }
    socket.emit('blind_box:fill', taskPopup.data)
    taskPopup.show = false
}

/**
 * 收到填充记录的显示
 */
const onFillTask = (current: number, total: number) => {
    showNotify({
        message: `填充进度${current}/${total}`,
        type: 'primary',
    })
}
</script>
<template>
    <template v-if="state">
        <CellGroup>
            <template #title>
                <div class="special_users">
                    <div class="title">特殊用户</div>
                    <Icon name="todo-list-o" @click="taskPopup.show = true" />
                    <Icon name="plus" @click="userPopup.show = true" />
                </div>
            </template>
            <div class="users">
                <Tag
                    v-for="uid in state.special_uids"
                    :key="uid"
                    type="primary"
                    :closeable="true"
                    size="large"
                    @close="removeUid(uid)"
                    >{{ uid }}</Tag
                >
            </div>
        </CellGroup>
        <Cell title="开关">
            <Space>
                <Button
                    size="small"
                    :type="state.no_record ? 'danger' : 'default'"
                    @click="toggleFlag('blind_box_no_record', 1 - state.no_record)"
                    >无记录：{{ state.no_record ? '开' : '关' }}</Button
                >
            </Space>
        </Cell>
        <CellGroup v-for="pool in state.pools" :key="pool.price" :title="`${pool.price}票盲盒`">
            <table class="table">
                <thead>
                    <tr>
                        <th :class="{ locked: pool.locked.includes(2) }" @click="toggleLocked(pool, 2)">中级</th>
                        <th :class="{ locked: pool.locked.includes(3) }" @click="toggleLocked(pool, 3)">高级</th>
                        <th :class="{ locked: pool.locked.includes(4) }" @click="toggleLocked(pool, 4)">特级</th>
                    </tr>
                    <tr>
                        <td>{{ pool.level_2.balance }}</td>
                        <td>{{ pool.level_3.balance }}</td>
                        <td>{{ pool.level_4.balance }}</td>
                    </tr>
                </thead>
                <tbody>
                    <tr v-for="i in pool.max_gifts" :key="i">
                        <td>
                            <GiftView :gift="pool.level_2.gifts[i - 1]" />
                        </td>
                        <td>
                            <GiftView :gift="pool.level_3.gifts[i - 1]" />
                        </td>
                        <td>
                            <GiftView :gift="pool.level_4.gifts[i - 1]" />
                        </td>
                    </tr>
                </tbody>
            </table>
        </CellGroup>
    </template>
    <Popup v-model:show="userPopup.show" position="top">
        <Field label="用户ID" inputAlign="right" v-model="userPopup.value"></Field>
        <div class="button-container"><Button type="primary" :block="true" @click="addUser">提交</Button></div>
    </Popup>
    <Button class="float-refresh" icon="replay" :round="true" @click="refreshState"></Button>
    <Popup v-model:show="taskPopup.show" position="top">
        <Field label="用户ID" inputAlign="right" v-model="taskPopup.data.uid"></Field>
        <Cell title="盲盒类型">
            <RadioGroup v-model="taskPopup.data.dealer_id" direction="horizontal">
                <Radio :name="0">13</Radio>
                <Radio :name="1">4</Radio>
                <Radio :name="38">1</Radio>
            </RadioGroup>
        </Cell>
        <Cell title="数量" v-model="taskPopup.data.num">
            <Stepper v-model="taskPopup.data.num" :min="1" :step="1" />
        </Cell>
        <div class="button-container"><Button type="primary" :block="true" @click="fillRecords">提交</Button></div>
    </Popup>
</template>
<style lang="scss" scoped>
.table {
    width: 100%;
    border-spacing: 0;
    border-collapse: collapse;
    background-color: #fff;

    th {
        font-size: 12px;
        color: #666;
    }

    td {
        font-size: 14px;
    }

    th,
    td {
        border: 1px solid #eee;
        padding: 8px 0;
        text-align: center;
        font-weight: normal;

        &.locked {
            background-color: var(--van-red);
            color: #fff;
        }
    }
}

.special_users {
    display: flex;
    align-items: center;
    justify-content: space-between;
}

.users {
    display: flex;
    flex-wrap: wrap;
    padding: 12px 0 0 16px;

    .van-tag {
        flex-shrink: 0;
        margin-right: 16px;
        margin-bottom: 12px;
    }
}

.button-container {
    padding: 12px 16px;
}

.float-refresh {
    right: 20px;
    bottom: 100px;
    position: fixed;
}
</style>
